<template>
  <div class="app-container">
    <el-form :model="searchForm" ref="searchFormRef" inline v-show="showSearch">
      <el-form-item label="字典名称" prop="where.type">
        <el-select v-model="searchForm.where.type" class="w-140px" disabled>
          <el-option v-for="item in typeOptions" :key="item.type" :label="item.name" :value="item.type" />
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签" prop="like.label">
        <el-input v-model="searchForm.like.label" placeholder="请输入字典标签" clearable @keyup.enter="search" />
      </el-form-item>
      <el-form-item label="状态" prop="where.status">
        <el-select v-model="searchForm.where.status" placeholder="数据状态" clearable class="w-120px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="search">搜索</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="mb-8px w-full">
      <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPerm="['system:dict-data:add']"
        >新增</el-button
      >
      <el-button
        type="success"
        plain
        icon="Edit"
        :disabled="ids.length !== 1"
        @click="handleEdit"
        v-hasPerm="['system:dict-data:edit']"
        >修改</el-button
      >
      <el-button
        type="danger"
        plain
        icon="Delete"
        :disabled="!ids.length"
        @click="handleDelete"
        v-hasPerm="['system:dict-data:delete']"
        >删除</el-button
      >
      <el-button type="warning" plain icon="Close" @click="closeTab">关闭</el-button>
      <right-toolbar v-model:showSearch="showSearch" @refresh="getList"></right-toolbar>
    </div>

    <el-table v-loading="loading" :data="listData" @selection-change="handleSelection">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="55" />
      <el-table-column label="字典标签" align="center" prop="label">
        <template #default="{ row }">
          <span v-if="!row.list_class || row.list_class === 'default'" :class="['dict-default', row.css_class]">{{
            row.label
          }}</span>
          <el-tag v-else :type="row.list_class" :class="row.css_class">{{ row.label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="字典键值" align="center" prop="value" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="字典排序" align="center" prop="list_sort" width="80" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="默认" align="center" prop="is_default" width="80">
        <template v-slot="{ row }">
          <dict-tag :options="sys_yes_no" :value="row.is_default" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="create_time" width="140">
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleEdit(scope.row)"
            v-hasPerm="['system:dict-data:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPerm="['system:dict-data:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="searchForm.pageNum"
      v-model:limit="searchForm.pageSize"
      @pagination="getList" />
    <dict-data-form v-model="formShow" :row="formData" :module-name="moduleName" @submit="getList" v-if="formShow" />
  </div>
</template>

<script setup name="DictData">
  import useDictStore from '@/store/modules/dict'
  import { listDataApi, delDataApi } from '@/api/system/dict/data'
  import { infoTypeApi } from '@/api/system/dict/type'
  import DictDataForm from './dataForm.vue'

  const { proxy } = getCurrentInstance()
  const moduleName = ref('字典数据')
  const showSearch = ref(true)
  const searchForm = ref({
    pageNum: 1,
    pageSize: 10,
    where: { type: undefined, status: undefined },
    like: { label: undefined },
    orderByColumn: 'list_sort',
    orderBySort: 'asc'
  })
  const { sys_normal_disable, sys_yes_no } = proxy.useDict('sys_normal_disable', 'sys_yes_no')

  // 初始化
  const route = useRoute()
  const dictId = ref('')
  onMounted(() => {
    dictId.value = route.params?.dictId || ''
    getTypeData()
  })

  // 查询列表
  const loading = ref(true)
  const total = ref(0)
  const listData = ref([])
  function getList() {
    loading.value = true
    listDataApi(searchForm.value).then(res => {
      listData.value = res?.list || []
      total.value = res?.total || 0
      loading.value = false
    })
  }

  // 根据请求参数获取字典类型
  const typeOptions = ref([])
  const dictType = ref('')
  function getTypeData() {
    if (!dictId.value) return proxy.$modal.msgWarning('参数缺失')
    infoTypeApi(dictId.value).then(res => {
      typeOptions.value = [{ type: res?.info?.type || '', name: res?.info?.name || '未知类型' }]
      dictType.value = res?.info?.type || ''
      reset()
    })
  }

  // 搜索和重置
  function search() {
    searchForm.value.pageNum = 1
    getList()
  }
  function reset() {
    proxy.resetForm('searchFormRef')
    searchForm.value.where.type = dictType.value
    search()
  }

  // 新增和编辑
  const formData = ref(null)
  const formShow = ref(false)
  function handleAdd() {
    formData.value = { type: dictType.value }
    formShow.value = true
  }
  function handleEdit(row) {
    const editId = row?.id || (ids.value.length ? ids.value[0] : '')
    if (!editId) return proxy.$modal.msgWarning('参数缺失')
    formData.value = { id: editId }
    formShow.value = true
  }

  // 删除按钮操作
  function handleDelete(row) {
    const delIds = row?.id || ids.value.join(',')
    if (!delIds) return proxy.$modal.msgWarning('未选择数据')
    proxy.$modal
      .confirm('是否确认删除字典编码为"' + delIds + '"的数据项？')
      .then(function () {
        return delDataApi(delIds)
      })
      .then(() => {
        useDictStore().removeDict(searchForm.value.dictType)
        proxy.$modal.msgSuccess('删除成功')
        getList()
      })
      .catch(() => {})
  }

  // 多选框选中数据
  const ids = ref([])
  function handleSelection(selection) {
    ids.value = selection.map(item => item.id)
  }

  // 返回按钮操作
  function closeTab() {
    proxy.$tab.closeOpenPage({ path: '/system/dict' })
  }
</script>
